import request, { wrap_api_func } from './request';

const BASE_URL = "/api/v1/usercenter"

export const login = wrap_api_func(async ({ nickname, password }) => {
    if (!nickname || !password) {
        throw new Error('缺少必要参数');
    }
    const { data } = await request.post(`${BASE_URL}/user/login`, { 
        nickname, 
        password 
    })
    return {
        code: data.code,
        msg: data.msg,
        data: data?.data ? {
            accessToken: data.data.accessToken,
            accessExpire: data.data.accessExpire,
            refreshAfter: data.data.refreshAfter,
        } : null
    }
});

function validateEmail(email) {
    const re = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    return re.test(email);
}

export const register = wrap_api_func(async ({ nickname, email, password }) => {
    if (!nickname || !email || !password) {
        throw new Error('缺少必要参数');
    }
    if (!validateEmail(email)) {
        throw new Error('邮箱格式错误');
    }
    const { data } = await request.post(`${BASE_URL}/user/register`, { 
        nickname,
        email,
        password 
    })
    return {
        code: data.code,
        msg: data.msg,
        data: data?.data ? {
            accessToken: data.data.accessToken,
            accessExpire: data.data.accessExpire,
            refreshAfter: data.data.refreshAfter,
        } : null
    }
});